package com.cc.controller;

import com.cc.model.EbComment;
import com.cc.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @RequestMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") int page,
                             @RequestParam(value = "pageSize", defaultValue = "3") int pageSize) {
        //1.获取新闻表的第一页数据，每页三条
        List<EbComment> comments = commentService.list(page, pageSize);
        int maxPage = commentService.getMaxPage(pageSize);
        //2.将数据（list）和视图（jsp）返回String
        ModelAndView mv = new ModelAndView();
        //绑定数据
        mv.addObject("comments", comments);
        //绑定视图
        mv.addObject("curPage", page);
        mv.addObject("maxPage", maxPage);
        mv.setViewName("manage/comment");
        return mv;
    }
    @RequestMapping("/edit")
    public String edit(Model model, Integer ecId){
        //1.根据新闻的编号查询新闻的详细信息
        EbComment ebComment = commentService.selectByCondition(ecId);
        //2.将查出来的新闻信息传递给comment-modify.jsp
        model.addAttribute("ebComment",ebComment);
        //System.out.println(ebComment);
        return"manage/comment-modify";
    }
    @RequestMapping("/editSubmit")
    public String editSubmit(EbComment ebComment){
        //1.更新留言信息
        int result = commentService.updateById(ebComment);
        //2.跳转到更新结果页面
        if (result<=0){
            return "manage/manage-error";
        }
        return "manage/manage-result";
    }
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id){
        //1.参数校验
        //2.执行删除（真实项目中 delete from 表名 where id=?）
        int result = commentService.delete(id);
        if (result==0){
            //TODO 要么return错误页面 要么跑出异常
        }
        return "manage/manage-result";
    }
}
